package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApUserSearchServiceImpl {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveUserSearch(Integer userId,String equipmentId,String keyword){
        //        记录搜索历史
        ApUserSearch userSearch = new ApUserSearch();




        userSearch.setUserId(userId);
        userSearch.setEquipmentId(equipmentId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());

//        当前登录人或这个设备id是否有这个记录
        Query query  = new Query();
        Criteria criteria = Criteria.where("keyword").is(keyword);
        if(userId==0){ //未登录
            criteria.and("equipmentId").is(equipmentId);
        }else{
            criteria.and("userId").is(userId);
        }
        long count = mongoTemplate.count(query, ApUserSearch.class);
        if(count==0){
            mongoTemplate.save(userSearch);
        }



    }

    public ResponseResult loadHistory(ApArticleSearchDto dto) {

        User user = UserThreadLocalUtil.get();
        //        当前登录人或这个设备id是否有这个记录
        Query query  = new Query();
        Criteria criteria = new Criteria();
        if(user.getUserId()==0){ //未登录
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else{
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }

        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.skip(0);
        query.limit(5);
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(apUserSearches);
    }

    public ResponseResult delHistory(ApArticleSearchDto dto) {

        List<ApUserSearch> hisList = dto.getHisList();

//        for (ApUserSearch userSearch : hisList) {
//            mongoTemplate.remove(new Query(Criteria.where("_id").is(userSearch.getId())));
//        }
        List<String> stringList = hisList.stream().map(ApUserSearch::getId).collect(Collectors.toList());
        mongoTemplate.remove(new Query(Criteria.where("_id").in(stringList)),ApUserSearch.class);
        return ResponseResult.okResult();

    }
}
